"""
悬浮窗组件

提供桌面悬浮窗功能，支持快速访问和操作
"""

import customtkinter as ctk
import tkinter as tk
from .themes import ModernTheme
import sys
import platform


class LogoFloatingWindow(ctk.CTk):
    """Logo悬浮窗 - 仅展示Logo的极简版本"""

    def __init__(self, use_emoji=False, dark_theme=True):
        super().__init__()

        # 主题配置
        self.dark_theme = dark_theme
        self.theme_colors = self._get_theme_colors()

        # Logo配置
        self.use_emoji = use_emoji
        self.logo_options = {
            "text": {"text": "MixVideo", "font_size": 24, "font_weight": "bold"}
        }

        # 基本配置
        self.title("MixVideo")
        self.geometry("180x80")
        self.resizable(False, False)

        # 强制置顶设置
        self.attributes("-topmost", True)
        self.attributes("-alpha", 0.5)
        self.wm_attributes("-topmost", True)  # 额外的置顶设置

        # 隐藏标题栏
        self.overrideredirect(True)

        # 设置窗口背景为透明/与主题一致
        self.configure(fg_color=self.theme_colors["bg_primary"])

        # 设置主题
        ModernTheme.setup_theme()

        # 拖拽相关变量
        self.drag_start_x = 0
        self.drag_start_y = 0
        self.window_start_x = 0
        self.window_start_y = 0
        self.is_dragging = False

        # 置顶控制
        self.always_on_top = True

        # 创建界面
        self.create_logo_interface()

        # 绑定事件
        self.bind_logo_events()

        # 设置位置
        self.position_logo_window()

    def _get_theme_colors(self):
        """获取主题颜色配置"""
        if self.dark_theme:
            return {
                "bg_primary": "#1a1a1a",  # 深色主背景
                "bg_secondary": "#2d2d2d",  # 深色次背景
                "bg_card": "#333333",  # 深色卡片背景
                "border_color": "#4a9eff",  # 蓝色边框
                "border_hover": "#66b3ff",  # 悬停边框
                "text_primary": "#ffffff",  # 白色主文字
                "text_secondary": "#b3b3b3",  # 灰色次文字
                "accent": "#4a9eff",  # 强调色
                "accent_hover": "#66b3ff",  # 悬停强调色
                "shadow": "rgba(0,0,0,0.5)",  # 阴影
            }
        else:
            return {
                "bg_primary": "#f5f5f5",
                "bg_secondary": "#ffffff",
                "bg_card": "#ffffff",
                "border_color": "#007AFF",
                "border_hover": "#0056CC",
                "text_primary": "#000000",
                "text_secondary": "#666666",
                "accent": "#007AFF",
                "accent_hover": "#0056CC",
                "shadow": "rgba(0,0,0,0.1)",
            }

    def create_logo_interface(self):
        """创建Logo界面"""
        # 主容器 - 方形设计，使用深色主题，无边框避免黑边
        self.main_frame = ctk.CTkFrame(
            self,
            fg_color=self.theme_colors["bg_primary"],
            corner_radius=0,  # 移除圆角，使用方形
            border_width=0,  # 移除边框避免黑边
        )
        self.main_frame.pack(fill="both", expand=True, padx=0, pady=0)

        # Logo标签 - 根据配置选择emoji或文字
        logo_config = self.logo_options["emoji" if self.use_emoji else "text"]
        self.logo_label = ctk.CTkLabel(
            self.main_frame,
            text=logo_config["text"],
            font=ctk.CTkFont(
                size=logo_config["font_size"], weight=logo_config["font_weight"]
            ),
            text_color=self.theme_colors["accent"],
        )
        self.logo_label.pack(expand=True)

        # 绑定拖拽事件到Logo
        self.logo_label.bind("<Button-1>", self.start_drag)
        self.logo_label.bind("<B1-Motion>", self.on_drag)
        self.logo_label.bind("<ButtonRelease-1>", self.stop_drag)

        # 绑定双击事件
        self.logo_label.bind("<Double-Button-1>", self.on_double_click)

    def bind_logo_events(self):
        """绑定Logo事件"""
        # 键盘快捷键
        self.bind("<Escape>", lambda _: self.destroy())

        # 鼠标悬停效果
        self.logo_label.bind("<Enter>", self.on_hover_enter)
        self.logo_label.bind("<Leave>", self.on_hover_leave)

        # 焦点事件 - 失去焦点时重新置顶
        self.bind("<FocusOut>", self.on_focus_out)
        self.bind("<FocusIn>", self.on_focus_in)

    def position_logo_window(self):
        """设置Logo窗口位置到右上角"""
        self.update_idletasks()
        screen_width = self.winfo_screenwidth()

        # 直接使用设置的窗口尺寸，不依赖检测
        window_width = 180  # 设置的宽度
        window_height = 60  # 设置的高度

        # 计算右上角位置，留出一些边距
        margin = 10
        x = screen_width - window_width - margin
        y = margin

        self.geometry(f"+{x}+{y}")
        print(f"屏幕宽度: {screen_width}")
        print(f"窗口尺寸: {window_width}x{window_height}")
        print(f"计算公式: x = {screen_width} - {window_width} - {margin} = {x}")
        print(f"计算公式: y = {margin} = {y}")
        print(f"悬浮窗位置: 右上角 ({x}, {y})")

    def on_focus_out(self, _):
        """失去焦点时重新置顶"""
        try:
            self.after(100, self.force_topmost)  # 延迟100ms后重新置顶
        except:
            pass

    def on_focus_in(self, _):
        """获得焦点时确保置顶"""
        try:
            self.force_topmost()
        except:
            pass

    # 拖拽事件处理
    def start_drag(self, event):
        """开始拖拽"""
        self.drag_start_x = event.x_root
        self.drag_start_y = event.y_root
        self.window_start_x = self.winfo_x()
        self.window_start_y = self.winfo_y()
        self.is_dragging = True

        # 拖拽时稍微增加透明度
        self.attributes("-alpha", 0.7)

    def on_drag(self, event):
        """拖拽中"""
        if self.is_dragging:
            dx = event.x_root - self.drag_start_x
            dy = event.y_root - self.drag_start_y
            new_x = self.window_start_x + dx
            new_y = self.window_start_y + dy
            self.geometry(f"+{new_x}+{new_y}")

    def stop_drag(self, _):
        """停止拖拽"""
        self.is_dragging = False
        # 恢复透明度
        self.attributes("-alpha", 0.9)

    def on_hover_enter(self, _):
        """鼠标悬停进入"""
        self.logo_label.configure(text_color=self.theme_colors["accent_hover"])
        # 可以添加背景色变化效果
        self.main_frame.configure(fg_color=self.theme_colors["bg_secondary"])

    def on_hover_leave(self, _):
        """鼠标悬停离开"""
        self.logo_label.configure(text_color=self.theme_colors["accent"])
        # 恢复原始背景色
        self.main_frame.configure(fg_color=self.theme_colors["bg_primary"])

    def on_double_click(self, _):
        """双击事件 - 打开主程序"""
        print("双击Logo - 打开主程序...")
        # 这里可以添加打开主程序的逻辑
        self.open_main_app()

    def refresh_logo(self):
        """刷新Logo"""
        # 简单的刷新动画
        original_text = self.logo_label.cget("text")
        self.logo_label.configure(text="↻")
        self.after(500, lambda: self.logo_label.configure(text=original_text))
        print("Logo已刷新")

    def open_main_app(self):
        """打开主程序"""
        print("从Logo悬浮窗打开主程序...")


class MiniFloatingWindow(LogoFloatingWindow):
    """迷你悬浮窗 - 兼容性别名，实际使用Logo悬浮窗"""

    pass


# 悬浮窗管理器
class FloatingWindowManager:
    """悬浮窗管理器"""

    def __init__(self):
        self.floating_windows = {}
        self.mini_windows = {}

    def create_mini_window(
        self,
        window_id: str = "mini",
        use_emoji: bool = False,
        dark_theme: bool = True,
    ) -> LogoFloatingWindow:
        """创建Logo悬浮窗（迷你版）"""
        if window_id in self.mini_windows:
            window = self.mini_windows[window_id]
            window.deiconify()
            window.lift()
            return window

        window = LogoFloatingWindow(use_emoji=use_emoji, dark_theme=dark_theme)
        self.mini_windows[window_id] = window

        # 简化的关闭处理，避免递归
        def on_window_destroy():
            if window_id in self.mini_windows:
                del self.mini_windows[window_id]

        # 绑定窗口销毁事件
        window.bind("<Destroy>", lambda _: on_window_destroy())

        return window

    def create_logo_window(
        self,
        window_id: str = "logo",
        use_emoji: bool = False,
        dark_theme: bool = True,
    ) -> LogoFloatingWindow:
        """创建Logo悬浮窗"""
        return self.create_mini_window(
            window_id, use_emoji=use_emoji, dark_theme=dark_theme
        )

    def close_all_windows(self):
        """关闭所有悬浮窗"""
        for window in list(self.floating_windows.values()):
            try:
                window.destroy()
            except:
                pass
        for window in list(self.mini_windows.values()):
            try:
                window.destroy()
            except:
                pass
        self.floating_windows.clear()
        self.mini_windows.clear()


# 全局管理器实例
floating_manager = FloatingWindowManager()
